package smartterracedfieldsolution.smartteracedfieldsolution.service.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class AliyunOSSService {

    private OSS ossClient;

    @Value("${aliyun.oss.bucketName}")
    private String bucketName;

    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    public AliyunOSSService(OSS ossClient) {
        this.ossClient = ossClient;
    }

    /**
     * 上传文件到OSS
     * @param file 文件对象
     * @return 文件访问URL
     */
    public String uploadImage(MultipartFile file) throws IOException {
        try (InputStream inputStream = file.getInputStream()) {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = UUID.randomUUID() + fileExtension;

            // 上传文件
            ossClient.putObject(bucketName, fileName, inputStream);

            // 生成访问URL（使用配置的endpoint）
            return String.format("https://%s.%s/%s", bucketName, endpoint, fileName);
        } catch (OSSException | ClientException e) {
            throw new RuntimeException("OSS上传失败: " + e.getMessage());
        }
    }

    /**
     * 删除OSS文件
     */
    public void deleteFileByUrl(String fileUrl) {
        try {
            // 从URL中提取objectName
            String prefix = String.format("https://%s.%s/", bucketName, endpoint);
            String objectName = fileUrl.replace(prefix, "");
            ossClient.deleteObject(bucketName, objectName);
        } catch (OSSException | ClientException e) {
            throw new RuntimeException("OSS删除失败: " + e.getMessage());
        }
    }
}
